﻿@page "/CatTalk/Passages/update/{Id:int}"
<div>

    @if (passage != null) {
        <PageHeader Class="site-page-header" Title="修改" Subtitle="之后点击保存即可" BackIcon="@("backward")" />
        <Title Level="1">修改标题</Title>
        <Input @bind-Value="@passage.Title"></Input>
        <Title Level="1">修改文章</Title>
        <Vditor.Editor Upload="upload" Mode="wysiwyg" Height="400" MinHeight="200" @bind-Value="@passage.Body"></Vditor.Editor>
        <Button OnClick="UpdatePassage">更新文章</Button>
    } else {
        <Alert>
            @msg
        </Alert>
    }
</div>
@inject HttpClient _httpClient;
@inject IMessageService _MessageService;
@code {
    [Parameter]
    public int ID { get; set; } = 0;
    Passage? passage;
    string msg = "加载中";
    protected async override Task OnInitializedAsync() {
        try {
            var myPassage = await GobalManager.getPassageById(ID);
            if (myPassage == null) {
                msg = "加载失败！文章可能被删除了！或者后端服务器没打开！";
            } else {
                passage = myPassage;
            }
        }
        catch (Exception ex) {
            Console.WriteLine("加载失败！" + ex.Message);
        }
        StateHasChanged();
        await base.OnInitializedAsync();
    }
    Vditor.Models.Upload upload = new Vditor.Models.Upload() {
            Url = "api/UpLoad",
            Max = 10 * 1024 * 1024,
            Accept = "image/*,*.doc,*.docx,*.*",
            Multiple = true,
        };
    async void UpdatePassage() {
        try {
            using var resp = await _httpClient.PostAsJsonAsync(GobalManager.serverURL + "/UpdatePassage", passage);
            Console.WriteLine("Update Passage " + resp.StatusCode);
            if (resp.StatusCode == System.Net.HttpStatusCode.OK) {
                await _MessageService.Info("文章更新成功");
            } else if (resp.StatusCode == System.Net.HttpStatusCode.FailedDependency) {
                await _MessageService.Error("文章不存在，可能已经删除了");
            }
        }
        catch (Exception ex) {
            Console.WriteLine("Error " + ex.Message);
        }
    }
}
